package com.ai.aiagent.service.impl;

import com.ai.aiagent.entity.MysqlChatMemory;
import com.ai.aiagent.repository.MysqlChatMemoryRepository;
import com.ai.aiagent.service.MysqlChatMemoryService;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MysqlChatMemoryServiceImpl implements MysqlChatMemoryService {

    @Autowired
    private MysqlChatMemoryRepository mysqlChatMemoryRepository;

    @Override
    public void save(Long conversationId, String promptType, List<Message> messages) throws JsonProcessingException {
        MysqlChatMemory mysqlChatMemory = new MysqlChatMemory();
        mysqlChatMemory.setChatMemoryConversationId(conversationId);
        mysqlChatMemory.setPromptType(promptType);
        mysqlChatMemory.setMessages(messages);
        mysqlChatMemoryRepository.save(mysqlChatMemory);
    }

    @Override
    public List<Message> get(Long conversationId) throws JsonProcessingException {
        Optional<MysqlChatMemory> mysqlChatMemoryFindone = mysqlChatMemoryRepository.findById(conversationId);
//        mysqlChatMemoryFindone.get().getMessages();
        return mysqlChatMemoryFindone.get().getMessages();
    }

    @Override
    public void clear(Long conversationId) {
        mysqlChatMemoryRepository.deleteById(conversationId);
    }
}
